<template>
  <div class="check_container" v-loading="loading">
    <el-form
      ref="formCheck"
      :model="formdata"
      label-width="80px"
      :rules="rules"
    >
      <el-form-item label="患者类型" prop="patientSource">
        <div class="pat_source">
          <el-radio-group
            v-model="formdata.patientSource"
            @change="chagnePatientSource"
          >
            <el-radio
              :size="size"
              v-for="item in patientTypeItemOptions"
              :key="item.value"
              :label="item.value"
              :disabled="isEditInfo"
            >{{item.name}}</el-radio>
          </el-radio-group>
        </div>
      </el-form-item>
      <el-row :gutter="5">
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <template v-if="applyInfoHospital === 'fuding' || hospitalCode === '12352203490467403B'">
            <el-form-item label="优先级">
              <el-select :size="size" ref="examClass" v-model="formdata.grade" filterable @change="gradeChange" style="width:100%;" clearable>
                <el-option
                  v-for="(item, index) in gradeList"
                  :key="index"
                  :value="item.item"
                  :label="item.item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="保密级别">
              <el-select :size="size" ref="examClass" v-model="formdata.privacyLevel" filterable style="width:100%;" clearable>
                <el-option
                  v-for="(item, index) in privacyLevelList"
                  :key="index"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </template>
          <el-form-item label="姓名" prop="patientName">
            <div class="flex flex-row align-center form-height">
              <el-input ref="patientName" :size="size" v-model="formdata.patientName" placeholder="姓名" clearable>
                <el-button :size="size" slot="append" icon="el-icon-search" @click="openHisDialog" v-if="isShowApplyCheck"></el-button>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group :size="size" v-model="formdata.gender">
              <el-radio :label="1" style="margin-right: 4px;">男</el-radio>
              <el-radio :label="2" style="margin-right: 4px;">女</el-radio>
              <el-radio :label="9" style="margin-right: 4px;">其他</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="身份证" prop="idCard">
            <el-input :size="size" v-model="formdata.idCard" placeholder="身份证号" @blur="idCardBlur" @change="idCardChange" @input="handleInput" clearable></el-input>
          </el-form-item>
          <el-form-item label="出生日期" prop="birthDate">
            <el-date-picker
              ref="birthDate"
              :size="size"
              v-model="formdata.birthDate"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions"
              style="width: 100%;"
              @change="birthDateChange"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="年龄" prop="patientAge">
            <div class="flex flex-row align-center form-height">
              <el-input :size="size" ref="patientAge" v-model="formdata.patientAge" @change="ageChange" placeholder="年龄" clearable>
                <el-select
                  :size="size"
                  v-model="formdata.patientAgeUnit"
                  slot="append"
                  @change="ageChange"
                  style="width: 66px;"
                  clearable
                >
                  <el-option
                    label="岁"
                    value="岁"
                  ></el-option>
                  <el-option
                    label="月"
                    value="月"
                  ></el-option>
                  <el-option
                    label="天"
                    value="天"
                  ></el-option>
                </el-select>
              </el-input>
            </div>
          </el-form-item>
          <el-form-item label="门诊号" prop="clinicCode" v-if="isAddInOutPatient">
            <el-input :size="size" v-model="formdata.clinicCode" placeholder="门诊号" clearable></el-input>
          </el-form-item>
          <el-form-item label="住院号" prop="visitNo" v-if="isAddInOutPatient">
            <el-input :size="size" v-model="formdata.visitNo" placeholder="住院号" clearable></el-input>
          </el-form-item>
          <el-form-item label="床位号" prop="bedNo">
            <el-input :size="size" v-model="formdata.bedNo" placeholder="床位号" clearable></el-input>
          </el-form-item>
          <el-form-item label="联系地址" prop="address">
            <el-input :size="size" v-model="formdata.address" placeholder="联系地址" clearable></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="patientPhone">
            <el-input :size="size" v-model="formdata.patientPhone" placeholder="联系电话" clearable></el-input>
          </el-form-item>
          <el-form-item label="申请医生" prop="applyDoctor">
            <el-select
              :size="size"
              v-model="formdata.applyDoctor"
              placeholder="请选择"
              clearable
              filterable
              allow-create
              ref="applyDoctor"
              style="width:100%">
              <el-option
                v-for="(item,index) in doctorListOptions"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <!--<el-input  ref="applyDoctor" v-model="formdata.applyDoctor" placeholder="申请医生"></el-input>-->
          </el-form-item>
          <el-form-item label="申请科室" prop="applyDepartment">
            <el-select
              :size="size"
              v-model="formdata.applyDepartment"
              placeholder="请选择"
              clearable
              filterable
              allow-create
              ref="applyDepartment"
              style="width:100%">
              <el-option
                v-for="(item,index) in departmentOptions"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <!--<el-input ref="applyDepartment" v-model="formdata.applyDepartment" placeholder="申请科室"></el-input>-->
          </el-form-item>
          <el-form-item label="申请时间" prop="applyDateTime">
            <el-date-picker
              :size="size"
              v-model="formdata.applyDateTime"
              type="datetime"
              :disabled="isEditInfo"
              placeholder="选择日期时间"
              style="width: 100%;"
              clearable
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="病史" prop="diseasesHistory">
            <el-input
              :size="size"
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 10 }"
              v-model="formdata.diseasesHistory"
              placeholder="病史"
              ref="diseasesHistory"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="临床诊断" prop="clinicdiagnosis">
            <el-input
              :size="size"
              type="textarea"
              ref="clinicdiagnosis"
              :autosize="{ minRows: 3, maxRows: 10 }"
              v-model="formdata.clinicdiagnosis"
              placeholder="临床诊断"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="检查目的" prop="examPurpose">
            <el-input :size="size" type="textarea" v-model="formdata.examPurpose" placeholder="检查目的" :autosize="{ minRows: 3, maxRows: 10 }" clearable></el-input>
          </el-form-item>
          <el-form-item label="检查备注" prop="exammark">
            <el-input :size="size" type="textarea" v-model="formdata.exammark" placeholder="检查备注" :autosize="{ minRows: 3, maxRows: 10 }" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-form-item label="PID" prop="masterPatientIndexId" v-if="mipVisible">
            <!-- <el-input :size="size" v-model="formdata.masterPatientIndexId" placeholder="PID" clearable></el-input> -->
            <el-input :size="size" ref="masterPatientIndexId" v-model="formdata.masterPatientIndexId" placeholder="PID" clearable></el-input>
          </el-form-item>
          <!-- <el-form-item label="PID" prop="patientId" v-else>
            <el-input :size="size" v-model="formdata.patientId" placeholder="PID" clearable></el-input>
          </el-form-item> -->
          <el-form-item label="患者ID" prop="patientId">
            <el-input :size="size" v-model="formdata.patientId" placeholder="患者ID" clearable></el-input>
          </el-form-item>
          <el-form-item label="申请单号" prop="applyCode">
            <el-input :size="size" v-model="formdata.applyCode" placeholder="申请单号" :disabled="isEditInfo" clearable></el-input>
          </el-form-item>
          <el-form-item label="价格" prop="cost">
            <el-input :size="size" v-model="formdata.cost" placeholder="价格" clearable></el-input>
          </el-form-item>
          <el-form-item label="收费状态" prop="chargeStatus" v-if="isChargeMenu">
            <el-select :size="size" style="width:100%" v-model="formdata.chargeStatus" placeholder="请选择" clearable>
              <el-option
                v-for="item in options.checkStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否两癌" prop="cancerType" v-if="isChangeFeeType">
            <el-select :size="size" style="width:100%" v-model="formdata.cancerType" placeholder="请选择" clearable>
              <el-option
                v-for="item in cancerTypeOptions"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="影像区域">
            <el-select :disabled="isEditInfo && !isMpiOrPid" :size="size" v-model="depArea" @change="depAreaChange" style="width:100%;" clearable>
              <el-option
                v-for="(item, index) in depAreaOptions"
                :key="index"
                :value="item"
                :label="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备类型">
            <el-select :size="size" :disabled="isEditInfo && !isMpiOrPid" ref="examClass" v-model="formdata.examClass" filterable @change="examClassChange" style="width:100%;" clearable>
              <el-option
                v-for="(item, index) in modalitytypeOptions"
                :key="index"
                :value="item"
                :label="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- this.hospitalCodeForm || this.hospitalCode -->
          <template v-if="applyInfoHospital != 'fuding' && hospitalCode != '12352203490467403B'">
            <el-form-item label="优先级">
              <el-select :size="size" ref="examClass" v-model="formdata.grade" filterable @change="gradeChange" style="width:100%;" clearable>
                <el-option
                  v-for="(item, index) in gradeList"
                  :key="index"
                  :value="item.item"
                  :label="item.item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="保密级别">
              <el-select :size="size" ref="examClass" v-model="formdata.privacyLevel" filterable style="width:100%;" clearable>
                <el-option
                  v-for="(item, index) in privacyLevelList"
                  :key="index"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </template>
          <el-form-item v-if="['CT','XRAY','MR','DR','MG', 'RF'].indexOf(formdata.examClass) > -1 && isToPrint" label="胶片打印" prop="checkcs">
            <el-checkbox v-model="formdata.checkcs" :true-label="'打胶片'" :false-label="''" @change="handleCheckcsChange">打胶片</el-checkbox>
          </el-form-item>
          <el-form-item label="大部位" prop="bigpart">
            <el-input :size="size" type="textarea" readonly :rows="1" v-model="formdata.bigpart" placeholder="请选择下方大部位"></el-input>
          </el-form-item>
          <el-form-item label="小部位2" prop="smallpart">
            <el-input :size="size" type="textarea" readonly :rows="3" v-model="formdata.smallpart" placeholder="请选择下方小部位"></el-input>
          </el-form-item>
          <el-form-item prop="examItemsData" class="tree form_item_m0 el-tree-style">
            <VirtualTree
              ref="tree"
              :data="checkTypeOptions"
              show-checkbox
              node-key="id"
              @check="handleCheckChange"
              :auto-expand-parent="defaultIsExpand"
              :default-expand-all="defaultIsExpand"
              :props="defaultProps"
              :filter-node-method="filterNode"
              render-after-expand
              :empty-text.sync="emptyRextTree"
              :height.sync="heightTree">
            </VirtualTree>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <HisRecordDialog ref="HisRecardDialog" v-if="isShowApplyCheck && isShowHisDialog"></HisRecordDialog>
  </div>
</template>

<script>
import {
  getidgenerator,
  // getItemList,
  // getDepAreaList,
  getHisTree,
  getModalityTypeList,
  getSysHospitalGetModelByCode
} from '@/api/api'
import {
  dateFormatter,
  isIdCard,
  sexById,
  birthdayById,
  birthdayByAge
  // getNewUUID
} from '@/utils/validate'
import { getLocalStorage } from '@/utils/localStorage'
import { getHISRecordDialogMemory, isNull } from '@/utils/utils'
import enc from '@/utils/aes'
import HisRecordDialog from './hisRecordDialog'
import VirtualTree from '@/assets/js/tree/index.js'
import applyInfo from '@/mixin/applyInfo'
import { Options } from '@/utils/constant'
const CHECK_FORM_DEFAULT_KEY = 'CHECK_FORM_DEFAULT'
import bus from '@/api/bus'
import { mapGetters } from 'vuex'
let string = '' // getLocalStorage('localSetMemory') || `{"modalitytype":"","depArea":"","areaName":"","dep":""}`
let localSetMemoryObj = '' // JSON.parse(string)
// let localSetMemoryObj = ''
export default {
  components: {
    VirtualTree, HisRecordDialog
  },
  mixins: [applyInfo],
  props: {
    checkUrl: {
      type: String,
      default: ''
    },
    fromAppointType: {
      type: Boolean,
      default: false
    },
    dialogVisibleEditAppo: {
      type: Boolean,
      default: false
    },
    isEditInfo: {
      type: Boolean,
      default: false
    },
    hospitalCodeForm: {
      String,
      default: ''
    },
    hospitalNameForm: {
      String,
      default: ''
    }
  },
  data() {
    return {
      // mipVisible: false,
      // privacyLevelList: [], // 保密级别列表
      size: 'default',
      isShowHisDialog: false,
      defaultIsExpand: false,
      // isShowApplyCheck: window.g.IS_APPLYCHECK_PICKHIS, // 玉环特有的人民医院需要手工选择his记录
      isChargeMenu: window.g.isChargeMenu, // 毕节手工登记添加收费状态
      isMpiOrPid: window.g.isMpiOrPid,
      // isChangeFeeType: window.g.ISUSE_DEFAULTSTEPTIME, // 玉环手工登记添加两癌判断以收费状态
      isChangeInfo: false, // 判断是否来自改约
      clickNodes: [],
      checkTypeAll: [],
      loading: false,
      isEncrypt: true,
      pubcliKey: null,
      userCode: this.$store.state.user.userCode,
      userName: this.$store.state.user.userName,
      hospitalCode: this.$store.state.user.hospitalCode,
      hospitalName: this.$store.state.user.hospitalName,
      applyInfoHospital: window.g.applyInfoHospital,
      depArea: localSetMemoryObj.depArea,
      options: Options,
      isEditOrChange: '',
      formdata: {
        bigpart: '',
        smallpart: '',
        patientId: '', // 病人id
        masterPatientIndexId: '', // 主索引
        idCard: '', // 身份证
        ssnCardNo: '', // 社保卡
        patientName: '绿1', // 姓名
        birthDate: '', // 出生日期
        gender: 1, // 性别 值域：0-未知的性别；1-男性；2-女；9-未说明的性别
        'address': '', // 联系地址
        'patientPhone': '', // 联系电话
        organizationCode: this.$store.state.user.hospitalCode, // 档案所属机构
        'visitNo': '', // 就诊号
        'visitNumber': 0, // 住院次数
        patientAge: '', // 年龄 21Y/8M/9D/10H
        patientAgeUnit: '岁', // 21Y/8M/9D/10H
        patientSource: 4, // 值域：1-门诊；2-住院；3-体检；4-绿检；5-急诊
        'medicalCardNo': '', // 就诊卡号
        'medicalRecordNo': '', // 病历号
        'clinicCode': '', // 门诊号
        'hospizationCode': '', // 住院号
        visitDateTime: dateFormatter(new Date()), // 就诊时间
        visitDeparmentCode: '', // 就诊科室代码
        visitDeparment: '', // 就诊科室
        attendDoctorCode: '', // 接诊医生代码
        attendDoctor: '', // 就诊医生
        diagnosis: '', // 诊断
        icD10: '', // icd10
        bedNo: '', // 床号
        wardName: '', // 病区
        wardNo: '', // 病区代码
        roomNo: '', // 病房号
        grade: '', // 优先级
        // emergencylabel: '',
        applyCode: '', // 申请单号
        'medicalAdviceNo': '', // 医嘱号
        examClass: localSetMemoryObj.modalitytype, // 申请单类型  类型代码:CT/MRI/US等  检查部门
        'examClassCode': '', // 申请单类型代码
        'clinicdiagnosis': '', // 临床诊断
        'chiefComplaint': '', // 主诉
        'diseasesHistory': '', // 电子病史
        'physicalSign': '', // 体征
        'allergicHistory': '', // 过敏史
        'drugResistanceHistory': '', // 耐药史
        'examPurpose': '', // 检查目的
        'exammark': '', // 检查备注
        'isEmergency': true,
        applyDepartment: this.$store.state.user.deptName, // 申请单科室
        applyDepartmentCode: this.$store.state.user.deptCode, // 申请科室代码
        applyDoctor: this.$store.state.user.userName, // 申请医生
        applyDoctorCode: this.$store.state.user.userCode, // 申请医生代码
        examText: '', // 申请单项目
        cost: '0', // 总价
        examExecuteDepartmentCode: '', // 执行科室代码
        examExecuteDepartment: null, // 执行科室
        'remarkInfo': '', // 备注
        'effectiveFlag': true,
        applyDateTime: dateFormatter(new Date()), // 申请时间
        examStatus: 5, // 值域：0-已登记；1-已检查；2-已报告；3-已审核；4-已作废；5-原始；
        feeStatus: !window.g.CHECK_APPLY_DEPAREA, // 是否收费
        invoiceNo: '',
        examItemsData: [], // 胸部平扫
        examItems: [], // 检查项目
        chargeStatus: '未收费', // 收费状态
        cancerType: '',
        radioDoctor: '',
        gastroscopicMedicine: '',
        material: '',
        transportTools: '',
        transportType: '',
        treatmentType: '',
        checkcs: ''
      },
      rules: {
        chargeStatus: [{ required: false, message: '请选择收费状态', trigger: 'blur' }],
        bigpart: [{ required: true, message: '大部位不能位空', trigger: 'blur' }],
        smallpart: [{ required: true, message: '小部位不能位空', trigger: 'blur' }],
        patientId: [{ required: true, message: '请输入患者ID', trigger: 'blur' }],
        masterPatientIndexId: [{ required: true, message: '请输入PID', trigger: 'blur' }],
        patientName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        patientAge: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
        birthDate: [{ required: true, message: '请选择出生日期', trigger: 'blur' }],
        patientSource: [{ required: true, message: '请选择病人类型', trigger: 'blur' }],
        gender: [{ required: true, message: '请选择性别', trigger: 'blur' }],
        visitDateTime: [{ required: true, message: '请选择就诊时间', trigger: 'blur' }],
        // applyDepartment: [{ required: true, message: '请选择申请科室', trigger: 'change' }],
        // applyDoctor: [{ required: true, message: '请选择申请医生', trigger: 'change' }],
        examClass: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
        // examItemsData: [{ required: true, message: '请选择检查项目', trigger: 'change' }],
        applyCode: [{ required: true, message: '请输入申请单号', trigger: 'blur' }],
        cost: [{ required: true, message: '请输入价格', trigger: 'blur' }],
        idCard: [{
          pattern: /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/,
          message: '证件号码格式有误！',
          trigger: 'blur'
        }]
      },
      // patSourceOptions: Options.patientTypeItemOptions,
      examStatusOptions: [
        // 0-已登记；1-已检查；2-已报告；3-已审核；4-已作废；5-原始；
        { value: 0, label: '已登记' },
        { value: 1, label: '已检查' },
        { value: 2, label: '已报告' },
        { value: 3, label: '已审核' },
        { value: 4, label: '已作废' },
        { value: 5, label: '原始' }
      ],
      pickerOptions: {
        disabledDate(time) {
          // 这个是当前日期后的日期不可选
          return time.getTime() > Date.now()
        }
      },
      // 项目值域
      checkTypeSelectFilter: '',
      filterIds: [],
      // departmentOptions: [],
      // doctorListOptions: [],
      // depAreaOptions: [],
      examItemsOptions: [], // 项目选项
      modalitytypeOptions: [],
      cancerTypeOptions: ['', '两癌筛查'],
      checkTypeOptions: [],
      filterData: [],
      defaultProps: {
        children: 'childrens',
        label: 'text'
      },
      // 预约
      appoint_type: window.g.APPOINT_TYPE || '前台登记', // 预约类型
      appoint_url: window.g.APPOINT_URL ? window.g.APPOINT_URL + '/index.html?isLogo=1' : ''
    }
  },
  computed: {
    ...mapGetters(['gradeList', 'privacyLevelList', 'departmentOptions', 'doctorListOptions', 'depAreaOptions']),
    appConfig() {
      let appConfig = this.$store.state.settings.appConfig
      return appConfig
    },
    isToPrint() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.isToPrint
    },
    isChangeCheckPos() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.isChangeCheckPos
    },
    isRequiredItems() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.isRequiredItems
    },
    isChangeFeeType() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.isChangeFeeType
    },
    isAddInOutPatient() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.isAddInOutPatient
    },
    isChooseAppointed() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.isChooseAppointed
    },
    emptyRextTree() {
      return this.formdata.examClass ? '暂无数据' : '请先选择检查设备'
    },
    heightTree() {
      return this.formdata.examClass && this.checkTypeOptions.length > 0 ? 320 : 0
    },
    applyCheckUrl: {
      get() {
        return this.checkUrl
      },
      set(val) {
        this.$emit('update:checkUrl', val)
      }
    },
    // 附件是否显示
    applyCheckFileSHow() {
      let appConfig = this.$store.state.settings.appConfig
      return appConfig &&
        appConfig.baseConfig &&
        appConfig.baseConfig.applyCheckFileSHow
    },
    isAddPrivacyLevel() {
      let appConfig = this.$store.state.settings.appConfig
      return appConfig &&
        appConfig.baseConfig &&
        appConfig.baseConfig.isAddPrivacyLevel
    },
    mipVisible() {
      let appConfig = this.$store.state.settings.appConfig
      return appConfig &&
        appConfig.baseConfig &&
        appConfig.baseConfig.mpi
    },
    isShowApplyCheck() {
      return (this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.isShowApplyCheck) || window.g.IS_APPLYCHECK_PICKHIS
    }
  },
  async created() {
    string = getLocalStorage('localSetMemory') || `{"modalitytype":"","depArea":"","areaName":"","dep":""}`
    localSetMemoryObj = JSON.parse(string)
    // if (this.appConfig.baseConfig && this.appConfig.baseConfig.mpi) {
    //   // this.mipVisible = this.appConfig.baseConfig.mpi
    //   this.mipVisible = this.appConfig.baseConfig.mpi
    // }
    if (this.applyInfoHospital === 'wzszxyy' || this.hospitalCode === '47052555733030211A1001') {
      this.formdata.applyDepartment = '' // 申请单科室
      this.formdata.applyDepartmentCode = '' // 申请科室代码
      this.formdata.applyDoctor = '' // 申请医生
      this.formdata.applyDoctorCode = '' // 申请医生代码
    }
    if (this.isShowApplyCheck) {
      let localSetMemoryObj = getHISRecordDialogMemory()
      this.formdata.examClass = localSetMemoryObj.modalitytype || ''
    }
    // console.error('this.formdata.examClass', this.formdata.examClass)
    // examClass: localSetMemoryObj.modalitytype || '', // 申请单类型  类型代码:CT/MRI/US等  检查部门
    this.formdata.examClass = !this.isEditInfo ? localSetMemoryObj.modalitytype || '' : null
    const checkFormDefault = getLocalStorage(CHECK_FORM_DEFAULT_KEY)
    if (checkFormDefault) {
      const cfd = JSON.parse(checkFormDefault)
      this.appoint_type = cfd.appoint_type && cfd.appoint_type != '' ? cfd.appoint_type : '前台登记'
    }
    this.applyCheckUrl = this.getCheckUrl()
    this.resetForm()
    if (this.isEditInfo) {
      this.getDepAreaList()
    } else {
      this.getDepAreaList().then(() => {
        this.getModalityTypeList().then(() => {
          this.getHisTree().then(() => {
            this.$nextTick(() => {
              this.checkTreeRow()
            })
          })
        })
      })
    }
    this.getDepartment()
    this.getDoctor()
    if (window.g.isSendParam || this.isRequiredItems) {
      const newRules = {
        // 新规则
        diseasesHistory: [{ required: true, message: '病史不能为空', trigger: 'blur' }],
        clinicdiagnosis: [{ required: true, message: '临床诊断不能为空', trigger: 'blur' }]
      }
      // 将新规则与现有规则合并
      const mergedRules = {
        ...this.rules, // 现有规则
        ...newRules // 新规则
      }
      // 更新规则
      this.rules = mergedRules
    }
  },
  async mounted() {
    console.log('mounted=>this.isEditInfo', this.isEditInfo)
    console.log('this.gradeList', this.gradeList)
    this.loading = this.isEditInfo
    bus.$off('VIPChange')
    bus.$on('VIPChange', (value) => {
      this.formdata.grade = value
    })
    bus.$off('JZChange')
    bus.$on('JZChange', (value) => {
      this.formdata.grade = value
    })
    this.getLevel()
    await this.getPrivacyLevel()
    bus.$off('currentRow')
    bus.$off('currentPatient')
    bus.$on('currentRow', (data) => {
      for (let key in data) {
        if (['patientName', 'idCard', 'wardName', 'bedNo', 'address', 'patientPhone', 'patientSource',
          'diseasesHistory', 'clinicdiagnosis', 'patientId', 'examClass', 'medicalRecordNo', 'visitNumber', 'masterPatientIndexId', 'checkcs'].indexOf(key) > -1) {
          if (data[key] || data[key] === 0 || data.price === '0') {
            this.formdata[key] = data[key]
          }
        }
      }
      this.formdata.birthDate = data.birthDate ? data.birthDate.substring(0, 10) : ''
      this.formdata.gender = data.gender || 1
      this.formdata.applyDateTime = dateFormatter(new Date()) // 申请时间

      // if (data.patientAge) {
      //   if (data.row[0].patientAge) {
      //     let lastLetterIndex = data.patientAge.length - 1
      //     this.formdata.patientAge = data.patientAge.substring(0, lastLetterIndex)
      //     this.formdata.patientAgeUnit = data.patientAge.substring(lastLetterIndex, data.patientAge.length)
      //   } else {
      //     if (!isNull(this.formdata.birthDate)) {
      //       this.setAgeValApply(this.formdata.birthDate)
      //     } else {
      //       this.formdata.patientAge = ''
      //       this.formdata.patientAgeUnit = ''
      //     }
      //   }
      // }
      const patientAge = data.patientAge || ''
      if (patientAge) {
        let lastLetterIndex = patientAge.length - 1
        this.formdata.patientAge = patientAge.substring(0, lastLetterIndex)
        this.formdata.patientAgeUnit = patientAge.substring(lastLetterIndex, patientAge.length)
      } else {
        // 若没年龄，则判断出生日期，从出生日期里面获取年龄
        if (!isNull(this.formdata.birthDate)) {
          this.setAgeValApply(this.formdata.birthDate)
        } else {
          this.formdata.patientAge = ''
          this.formdata.patientAgeUnit = ''
        }
      }
      if (data.price || data.price === 0 || data.price === '0') {
        this.formdata.cost = data.price + ''
      }
    })
    bus.$on('currentPatient', (data) => {
      let examination = data[0].examination
      const { patient, visit, examinations } = data[0].examination
      data.type === '1' ? this.resetForm(1) : null
      this.isEditOrChange = data.type
      // console.warn('来这里了', data)
      this.isChangeInfo = true
      // getAppointmentResultListByAccessno(data).then(res => {
      //   // 处理返回的数据
      if (data.length != 0) {
        let lastLetterIndex = 0
        if (data && data.row && data.row.length > 0) {
          const patientAge = data.row[0].patientAge || ''
          if (patientAge) {
            if (!isNull(patient.birthDate)) {
              this.formdata.birthDate = patient.birthDate.substring(0, 10)
            }
            lastLetterIndex = patientAge.length - 1
            this.formdata.patientAge = patientAge.substring(0, lastLetterIndex)
            this.formdata.patientAgeUnit = patientAge.substring(lastLetterIndex, patientAge.length)
          } else {
            // 若没年龄，则判断出生日期，从出生日期里面获取年龄
            if (!isNull(patient.birthDate)) {
              this.formdata.birthDate = patient.birthDate.substring(0, 10)
              this.setAgeValApply(this.formdata.birthDate)
            } else {
              this.formdata.patientAge = ''
              this.formdata.patientAgeUnit = ''
            }
          }
          this.hospitalName = data.row[0].hospitalName
        }
        if (examination) {
          const appointmentResultData = data[0].appointmentResultData
          const appointmentListDmb = data[0].appointmentListDmb
          this.hospitalCode = patient.organizationCode
          // let lastLetterIndex = visit.patientAge.length - 1
          const newData = {
            patientName: patient.patientName,
            organizationCode: patient.organizationCode,
            masterPatientIndexId: data.row[0].mpi || '',
            gender: patient.gender,
            idCard: patient.idCard,
            birthDate: patient.birthDate,
            patientPhone: patient.patientPhone,
            address: patient.address,
            patientId: patient.patientId,
            patientSource: data.type === '1' ? 4 : visit.patientSource,
            bedNo: visit.bedNo,
            wardName: visit.wardName,
            applyDoctor: examinations[0].applyDoctor,
            applyDepartment: examinations[0].applyDepartment,
            applyDateTime: examinations[0].applyDateTime,
            diseasesHistory: examinations[0].diseasesHistory,
            cost: data.type === '1' ? 0 : parseFloat(examinations[0].cost),
            feeStatus: data.type === '1' ? true : examinations[0].feeStatus,
            applyCode: data.type === '1' ? this.formdata.applyCode : examinations[0].applyCode,
            clinicdiagnosis: examinations[0].clinicdiagnosis,
            examClass: data.type === '1' ? (localSetMemoryObj.modalityType || appointmentListDmb.modalityType) : appointmentListDmb.modalityType,
            bigpart: examinations && examinations.length != 0 && data.type === '2' ? this.getBigPart(examinations[0]) : '',
            smallpart: examinations && examinations.length != 0 && data.type === '2' ? this.getSmallPart(examinations[0]) : '',
            grade: this.isMpiOrPid && data.type === '1' ? '中' : appointmentResultData.grade,
            depArea: data.type === '1' ? (localSetMemoryObj.depArea || appointmentListDmb.depArea) : appointmentListDmb.depArea,
            privacyLevel: appointmentResultData.privacyLevel,
            gastroscopicMedicine: examinations[0].gastroscopicMedicine,
            transportTools: examinations[0].transportTools,
            transportType: examinations[0].transportType,
            treatmentType: examinations[0].treatmentType,
            material: examinations[0].material,
            radioDoctor: appointmentResultData.radioDoctor
          }
          // console.error('...newData', newData)
          this.depArea = data.type === '1' ? (localSetMemoryObj.depArea || appointmentListDmb.depArea) : appointmentListDmb.depArea
          this.formdata = { ...this.formdata, ...newData }
          // this.birthDateChange()
          // console.error('...this.formdata', this.formdata)
        }
        this.$nextTick(() => {
          const bigpart = this.formdata.bigpart
          const smallpart = this.formdata.smallpart
          this.getModalityTypeList().then(() => {
            this.getHisTree().then(() => {
              this.formdata.bigpart = bigpart
              this.formdata.smallpart = smallpart
              // console.error('this.formdata.smallpart', this.formdata.smallpart)
              // console.error('this.formdata.bigpart', this.formdata.bigpart)
              this.checkTreeRow()
              this.loading = false
            })
          })
        })
      }
    })
  },
  beforeDestroy() {
    bus.$off('currentRow')
    bus.$off('VIPChange')
    bus.$off('JZChange')
  },
  // watch: {
  //   formdata: {
  //     deep: true,
  //     handler(newVal, oldVal) {
  //       // 把值传给当前的右边的页面
  //       // if (this.enterNum === 3) {
  //       this.$emit('manual-registration', this.formdata)
  //       // } else {
  //       //   this.enterNum++
  //       // }
  //     }
  //   }
  // },
  methods: {
    getDefaultGradeTypeValue() {
      // this.gradeList.findIndex(item => item.)
    },
    // 对获得的大部位数据进行处理
    getBigPart(bigpart) {
      let bigPartsSet = new Set()
      if (bigpart.examItems && bigpart.examItems.length !== 0) {
        bigpart.examItems.forEach(parts => {
          if (parts.examParts && parts.examParts.length !== 0) {
            bigPartsSet.add(parts.examParts[0].examPart)
          }
        })
      }
      let bigPartsArray = Array.from(bigPartsSet)
      return bigPartsArray.join(',')
    },
    // 对获得的小部位数据进行处理
    getSmallPart(smallpart) {
      let smallPartsSet = new Set()
      if (smallpart.examItems && smallpart.examItems.length !== 0) {
        smallpart.examItems.forEach(parts => {
          smallPartsSet.add(parts.examItemName)
        })
      }
      let smallPartsArray = Array.from(smallPartsSet)
      return smallPartsArray.join(',')
    },
    // 实现默认勾选
    checkTreeRow() {
      // // 考虑多个大小部位的情况
      let bp = this.formdata.bigpart.split(',')
      let sp = this.formdata.smallpart.split(',')
      let bsp = []
      // 将值整理后传给tree组件中封装的设置勾选的函数
      bp.forEach(item => {
        sp.forEach(item2 => {
          bsp.push({ 'id': item + item2 + '2' })
        })
      })
      // console.error('bsp', bsp)
      if (bsp.length > 0) {
        this.$nextTick(() => {
          this.$refs.tree && this.$refs.tree.setCheckedNodes ? this.$refs.tree.setCheckedNodes(bsp) : null
          if (this.applyInfoHospital != 'fuding' || this.$store.state.user.hospitalCode != '12352203490467403B') {
            !this.$hasPermission(['YJYY10008061']) && this.$refs.tree && this.$refs.tree.setDisabledNodes ? this.$refs.tree.setDisabledNodes(bsp) : null
          }
        })
      }
      // bp.forEach(item => {
      //   sp.forEach(item2 => {
      //     let nodeId = item + item2 + '2'
      //     console.error('来这里了', this.$refs.tree.getNode(nodeId))
      //     this.$set(this.$refs.tree.getNode(nodeId), 'disabled', true)
      //     // this.$set(node, 'disabled', true)
      //     // node.disabled = true
      //     // node.editable = false
      //     // console.log(`Node ${nodeId}: disabled=${node.disabled}, editable=${node.editable}`)
      //   })
      // })
    },
    setChangeInfo(type) {
      // 手动登记改约
      const validFlag = this.validForm()
      if (!validFlag) return
      const patList = this.getApplyData()
      console.log('$$$$$$patList$$$$$$', JSON.parse(JSON.stringify(patList)))
      const userInfo = this.$store.state.user.userInfo
      const applyIds = this.formdata.applyCode // 检查申请单编号（单独对指定申请单进行操作）
      const data = {
        type: 'rescheduling',
        source: type === '1' ? '' : 'editHisInfo',
        hospitalCode: this.hospitalCodeForm || this.hospitalCode,
        applyHospitalCode: this.hospitalCodeForm || this.hospitalCode,
        hospitalName: this.hospitalNameForm || this.hospitalName,
        patientId: this.formdata.patientId,
        operateUser: userInfo.userName,
        operateCode: userInfo.userCode,
        examClass: this.formdata.examClass,
        idCard: this.formdata.idCard,
        applyCode: applyIds,
        appointmentType: this.fromAppointType ? '检查科室' : this.appoint_type,
        tel: '',
        ps: this.formdata.patientSource,
        pw: 0, // 0 病人id 1 卡号 2 门诊号 3 住院号 4 发票号 5 申请单号 6 身份证号 7 社保卡号 暂时不用 8 手机号 默认0
        edm: this.formdata.examExecuteDepartment,
        isLogo: 1,
        yeFlag: 1,
        // 当前选择患者的所有申请单数据
        patientList: patList ? enc.AESEncrypt(JSON.stringify(patList), '3c837d501a8f49b1') : null
      }
      console.error('检查data====>grade', data)
      // if (patList) return
      if (window.g.UNRELOAD_APPO_EXAM) {
        this.applyCheckUrl = ''
        setTimeout(() => {
          this.applyCheckUrl = this.getCheckUrl()
          setTimeout(() => {
            this.$emit('editCheckInfo', data)
          }, 500)
        }, 200)
      } else {
        // bus.$emit('apply', data)
        this.$emit('editCheckInfo', data)
        // this.$refs.CheckIframe && this.$refs.CheckIframe.postMsg(data, '*')
      }
    },
    async getidgenerator() {
      return new Promise(async resolve => {
        const params = {
          HospitalCode: this.hospitalCodeForm || this.hospitalCode
        }
        await getidgenerator(params).then(res => {
          if (res && res.code === 10000 && res.content) {
            const id = res.content
            resolve(id)
          }
          resolve(new Date().getTime())
        })
      })
    },
    async getLevel() {
      let params = { HospitalCode: this.hospitalCodeForm || this.hospitalCode, Dep: this.$store.state.depArea || '', type: '优先级' }
      await this.$store.dispatch('settings/set_gradeList', params)
      let findResult = this.gradeList.findIndex(item => item.item == '普通')
      if (findResult > -1) {
        this.formdata.grade = '普通'
      }
    },
    async getPrivacyLevel() {
      let params = { HospitalCode: this.hospitalCodeForm || this.hospitalCode, type: '保密级别' }
      await this.$store.dispatch('settings/set_privacyLevelList', params)
    },
    async getDepartment() {
      let params = { HospitalCode: this.hospitalCodeForm || this.hospitalCode, type: '申请科室' }
      await this.$store.dispatch('settings/set_departmentOptions', params)
    },
    async getDoctor() {
      let params = { HospitalCode: this.hospitalCodeForm || this.hospitalCode, type: '申请医生' }
      await this.$store.dispatch('settings/set_doctorListOptions', params)
    },
    openHisDialog() {
      this.isShowHisDialog = true
      // this.$parent.$parent.$refs.HisRecardDialog.open()
      this.$nextTick(() => {
        this.$refs.HisRecardDialog.open()
      }, 200)
    },
    goSourceEnquiry() {
      this.$router.push('/check/sourceEnquiry')
    },
    getCheckUrl() {
      let registerRoom = getLocalStorage('UserPermision') || ''
      let string = this.appoint_url + `&v=${window.g.lcVERSION || window.g.VERSION}&yeFlag=1&hospitalCode=${this.hospitalCodeForm || this.hospitalCode}&hospitalName=${this.hospitalNameForm || this.hospitalName}&operateUser=${this.userName}&operateCode=${this.userCode}&appointmentType2=${this.appoint_type || ''}&appointmentType=${this.appoint_type || ''}`
      if (registerRoom) {
        string += '&registerRoom=' + registerRoom
      }
      string += '&patientId='
      return string
    },
    appointmentPostMessage() {
      const validFlag = this.validForm()
      if (!validFlag) return
      if (!this.appoint_url) {
        this.$message.info('未配置预约地址！')
        return
      } else {
        const patList = this.getApplyData()
        console.log('$$$$$$patList$$$$$$', JSON.parse(JSON.stringify(patList)))
        const userInfo = this.$store.state.user.userInfo
        const applyIds = this.formdata.applyCode // 检查申请单编号（单独对指定申请单进行操作）
        let data = {
          hospitalCode: this.hospitalCodeForm || this.hospitalCode,
          applyHospitalCode: this.hospitalCodeForm || this.hospitalCode,
          hospitalName: this.hospitalNameForm || this.hospitalName,
          patientId: this.formdata.patientId,
          // pid: this.formdata.patientId,
          // masterPatientId: this.formdata.masterPatientId,
          operateUser: userInfo.userName,
          operateCode: userInfo.userCode,
          examClass: this.formdata.examClass,
          idCard: this.formdata.idCard,
          applyCode: applyIds,
          appointmentType: this.appoint_type,
          tel: '',
          ps: this.formdata.patientSource,
          pw: 0, // 0 病人id 1 卡号 2 门诊号 3 住院号 4 发票号 5 申请单号 6 身份证号 7 社保卡号 暂时不用 8 手机号 默认0
          edm: this.formdata.examExecuteDepartment,
          isLogo: 1,
          yeFlag: 1,
          registerRoom: getLocalStorage('localSetMemory') ? JSON.parse(getLocalStorage('localSetMemory')).registerRoom : '',
          // 当前选择患者的所有申请单数据
          patientList: patList ? enc.AESEncrypt(JSON.stringify(patList), '3c837d501a8f49b1') : null,
          medicalRecordNo: this.formdata.medicalRecordNo,
          visitNumber: this.formdata.visitNumber
        }
        if (this.dialogVisibleEditAppo) {
          data['type'] = 'rescheduling'
        }
        console.warn('检查data====>', data)
        // if (patList) return
        if (window.g.UNRELOAD_APPO_EXAM) {
          this.applyCheckUrl = ''
          setTimeout(() => {
            this.applyCheckUrl = this.getCheckUrl()
            setTimeout(() => {
              this.$emit('applyCheckEmit', data)
            }, 500)
          }, 200)
        } else {
          this.$emit('applyCheckEmit', data)
          // this.$refs.CheckIframe && this.$refs.CheckIframe.postMsg(data, '*')
        }
      }
    },
    validForm() {
      if (!this.formdata.patientName) {
        this.$message.warning('患者姓名不能为空！')
        this.$refs.patientName.focus()
        return false
      } else if (!this.formdata.patientAge) {
        this.$message.warning('年龄不能为空！')
        this.$refs.patientAge.focus()
        return false
      } else if (!this.formdata.birthDate) {
        this.$message.warning('出生日期不能为空！')
        this.$refs.birthDate.focus()
        return false
      } else if ((window.g.isSendParam || this.isRequiredItems) && !this.formdata.diseasesHistory) {
        this.$message.warning('病史不能为空！')
        this.$refs.diseasesHistory.focus()
        return false
      } else if ((window.g.isSendParam || this.isRequiredItems) && !this.formdata.clinicdiagnosis) {
        this.$message.warning('临床诊断不能为空！')
        this.$refs.clinicdiagnosis.focus()
        return false
      } else if ((this.mipVisible) && !this.formdata.masterPatientIndexId) {
        this.$message.warning('PID不能为空')
        this.$refs.masterPatientIndexId.focus()
        return false
      }
      // else if (!this.formdata.applyDoctor) {
      //   this.$message.warning('申请医生不能位空！')
      //   this.$refs.applyDoctor.focus()
      //   return false
      // } else if (!this.formdata.applyDepartment) {
      //   this.$message.warning('申请科室不能位空！')
      //   this.$refs.applyDepartment.focus()
      //   return false
      // }
      if (!this.formdata.examClass) {
        this.$message.warning('设备类型不能为空！')
        this.$refs.examClass.focus()
        return false
      } else if (!this.formdata.bigpart) {
        this.$message.warning('大部位不能为空！')
        return false
      } else if (!this.formdata.smallpart) {
        this.$message.warning('小部位不能为空！')
        return false
      // } else if (!this.formdata.cost || this.formdata.cost === 0) {
      } else if (this.formdata.cost === undefined) {
        this.$message.warning('价格不能为空！')
        return false
      }
      return true
    },
    async depAreaChange() {
      // let params = {
      //   depArea: this.depArea
      // }
      // this.$utils.setHISRecordDialogMemory(params)
      await this.getModalityTypeList()
      this.getHisTree()
    },
    handleCheckChange() {
      this.$nextTick(() => {
        this.getTreeCheckedData('tree')
      })
    },
    getTreeCheckedData(treeModel) {
      // 如果一个父节点下面的子集都选择了，父级是全选的话，就提交一条数据，检查类型给数据，检查部位不用给了
      // 只有父级下面的自己部分选中的话，对应每个子集一条数据
      console.log('this.$refs[treeModel]', this.$refs[treeModel])
      let checkedNodes = this.$refs[treeModel].getCheckedNodes()
      console.log('checkedNodes', checkedNodes)
      const _bp = []
      const _sp = []
      checkedNodes.forEach(node => {
        if (node.level === 1) {
          _bp.push(node.text)
        } else if (node.level === 2) {
          _sp.push(node.text)
          if (!_bp.includes(node.parentId)) {
            // 判断父级是否已存在，如果没有，父级加入已选数据
            _bp.push(node.parentId)
          }
        }
      })
      // console.error('来这里了嘛', this.formdata.bigpart, )
      // 关于已预约列表绿检信息修改问题：切换到其他设备类型的时候可以追加部位，而不是把原来的清空掉
      // this.formdata.bigpart = this.isEditInfo ? this.formdata.bigpart + ',' + _bp.join(',') : _bp.join(',')
      // this.formdata.smallpart = this.isEditInfo ? this.formdata.bigpart + ',' + _sp.join(',') : _sp.join(',')
      this.formdata.bigpart = _bp.join(',')
      this.formdata.smallpart = _sp.join(',')

      this.appointmentPostMessage()
    },
    filterNode(value, data, node) {
      return this.filterNodeComm('filterIds', 'checkTypeSelectFilter', value, data, node)
    },
    // 实现默认勾选
    // checkTreeRow() {
    //   // 考虑多个大小部位的情况
    //   let bp = this.formdata.bigpart.split(',')
    //   let sp = this.formdata.smallpart.split(',')
    //   let bsp = []
    //   // 将值整理后传给tree组件中封装的设置勾选的函数
    //   bp.forEach(item => {
    //     sp.forEach(item2 => {
    //       bsp.push({ 'id': item + item2 + '2', disabled: true })
    //     })
    //   })
    //   // console.error('bsp', bsp)
    //   if (bsp.length > 0) {
    //     this.$nextTick(() => {
    //       this.$refs.tree.setCheckedNodes(bsp)
    //     })
    //   }
    // },
    // 检查类型过滤，公用函数
    filterNodeComm(idsKey, stFilter, value, data, node) {
      if ((this[`${idsKey}`].length == 0 && !value) || (typeof value === 'object' && value.length === 0)) {
        node ? node.expanded = false : null
        return true
      }
      if (typeof value === 'string') {
        let flag = false
        // 判断文字查询是否指定字段
        if (this[`${stFilter}`] && this[`${stFilter}`] * 1 === 2) {
          if (data.level === 3) {
            if (this[`${idsKey}`].length === 0 || this[`${idsKey}`].length > 0 && this[`${idsKey}`].indexOf(data.grandId) > -1) {
              if (data.parentId.indexOf(value) !== -1) {
                return true
              } else {
                return false
              }
            } else {
              return false
            }
          }
        }
        if (this[`${stFilter}`] && this[`${stFilter}`] * 1 === 3 && data.level === 2) {
          return false
        }

        if (this[`${idsKey}`].length === 0 && (data && data.text.indexOf(value) !== -1)) {
          flag = true
        } else if (this[`${idsKey}`].length > 0 && (this[`${idsKey}`].indexOf(data.parentId) > -1 || this[`${idsKey}`].indexOf(data.grandId) > -1) && data.text.indexOf(value) !== -1) {
          flag = true
        }
        return flag
      } else if (typeof value === 'object') {
        let flag = false
        for (let v of value) {
          if (v === data.text || this[`${idsKey}`].indexOf(data.parentId) > -1 || this[`${idsKey}`].indexOf(data.grandId) > -1) {
            flag = true
            this[`${idsKey}`].push(data.id)
          }
        }
        return flag
      }
    },
    gethospitalInfo(hospitalCode) {
      return new Promise(async resolve => {
        await getSysHospitalGetModelByCode({ hospitalCode }).then(res => {
          this.pubcliKey = res.content.guomiKey
          if (!window.g.API_ROOT_SCHEDULE) {
            window.g.API_ROOT_SCHEDULE = res.content.hiswebservice
          }
        })
        resolve()
      })
    },
    getApplyData() {
      const fd = this.formdata
      let params = {
        patient: {
          patientId: fd.patientId, // 病人id
          masterPatientIndexId: fd.masterPatientIndexId, // 主索引
          idCard: fd.idCard, // 身份证
          ssnCardNo: fd.ssnCardNo, // 社保卡
          patientName: fd.patientName, // 姓名
          birthDate: fd.birthDate, // 出生日期
          gender: fd.gender, // 性别 值域：0-未知的性别；1-男性；2-女；9-未说明的性别
          address: fd.address, // 联系地址
          patientPhone: fd.patientPhone, // 联系电话
          organizationCode: fd.organizationCode, // 档案所属机构
          grade: fd.grade, // 优先级
          gastroscopicMedicine: fd.gastroscopicMedicine,
          transportTools: fd.transportTools,
          transportType: fd.transportType,
          treatmentType: fd.treatmentType,
          material: fd.material,
          radioDoctor: fd.radioDoctor
        },
        visit: {
          visitNo: fd.visitNo, // 就诊号
          visitNumber: fd.visitNumber, // 住院次数
          patientAge: fd.patientAge + fd.patientAgeUnit, // 年龄
          patientSource: fd.patientSource, // 值域：1-门诊；2-住院；3-体检；5-急诊
          medicalCardNo: fd.medicalCardNo, // 就诊卡号
          medicalRecordNo: fd.medicalRecordNo, // 病例号
          clinicCode: fd.clinicCode, // 门诊号
          hospizationCode: fd.hospizationCode, // 住院号
          visitDateTime: fd.visitDateTime, // 就诊时间
          visitDeparmentCode: fd.visitDeparmentCode, // 就诊科室代码
          visitDeparment: fd.visitDeparment, // 就诊科室
          attendDoctorCode: fd.attendDoctorCode, // 接诊医生代码
          attendDoctor: fd.attendDoctor, // 就诊医生
          diagnosis: fd.diagnosis, // 诊断
          icD10: fd.icD10, // icd10
          bedNo: fd.bedNo, // 床号
          wardName: fd.wardName, // 病区
          wardNo: fd.wardNo, // 病区代码
          roomNo: fd.roomNo // 病房号
        },
        examinations: []
      }

      const examItems = this.getSelectedCheckPartData()
      let examinationsObj = {
        examItems,
        applyCode: fd.applyCode, // 申请单号
        medicalAdviceNo: fd.medicalAdviceNo, // 医嘱号
        examClass: fd.examClass, // 申请单类型  类型代码:CT/MRI/US等  检查部门
        examClassCode: fd.examClassCode, // 申请单类型代码
        clinicdiagnosis: fd.clinicdiagnosis, // 临床诊断
        chiefComplaint: fd.chiefComplaint, // 主诉
        diseasesHistory: fd.diseasesHistory, // 电子病史
        physicalSign: fd.physicalSign, // 体征
        allergicHistory: fd.allergicHistory, // 过敏史
        drugResistanceHistory: fd.drugResistanceHistory, // 耐药史
        examPurpose: fd.examPurpose, // 检查目的
        remarkInfo: fd.exammark, // 检查备注
        exammark: fd.exammark, // 检查备注
        isEmergency: fd.isEmergency,
        applyDepartment: fd.applyDepartment, // 申请单科室
        applyDepartmentCode: fd.applyDepartmentCode, // 申请科室代码
        applyDoctor: fd.applyDoctor, // 申请医生
        applyDoctorCode: fd.applyDoctorCode, // 申请医生代码
        examText: fd.examText, // 申请单项目
        cost: fd.cost ? Number(fd.cost) : 0, // 总价
        examExecuteDepartmentCode: fd.examExecuteDepartmentCode, // 执行科室代码
        examExecuteDepartment: fd.examExecuteDepartment, // 执行科室
        // remarkInfo: fd.remarkInfo, // 备注
        effectiveFlag: fd.effectiveFlag,
        applyDateTime: dateFormatter(new Date()), // 申请时间
        examStatus: fd.examStatus, // 值域：0-已登记；1-已检查；2-已报告；3-已审核；4-已作废；5-原始；
        isApply: 0,
        // feeStatus: this.isChangeFeeType ? fd.cancerType !== '' : (this.isChargeMenu ? fd.chargeStatus !== '未收费' : fd.feeStatus), // 是否收费
        feeStatus: this.isChargeMenu ? fd.chargeStatus !== '未收费' : fd.feeStatus, // 是否收费
        invoiceNo: fd.invoiceNo,
        visitNumber: fd.visitNumber,
        privacyLevel: fd.privacyLevel, // 保密级别
        gastroscopicMedicine: fd.gastroscopicMedicine,
        material: fd.material,
        radioDoctor: fd.radioDoctor,
        transportTools: fd.transportTools,
        transportType: fd.transportType,
        treatmentType: fd.treatmentType
      }
      this.isChangeFeeType ? examinationsObj.feeType = fd.cancerType : null
      params.examinations.push(examinationsObj)
      console.log('getApplyData_params', params)
      return [params]
    },
    getSelectedCheckPartData() {
      // 获取检查部位（level2）
      let checkedNodes = this.$refs.tree.getCheckedNodes()
      const examItems = []
      console.warn('checkedNodes', checkedNodes)
      checkedNodes.forEach(node => {
        if (node.level === 2) {
          const examItem = {
            'examItemNo': '', // 医技序号
            'examItemCode': '', // 项目代码
            'examItemName': node.text,
            'examMethod': '', // 检查方法
            'price': 0,
            'amount': 0,
            'feeStatus': true,
            'checkposCode:': node.remart,
            'examParts': []
          }
          const examPart = {
            'examPartCode': '', // 部位代码
            'examPart': node.parentId, // 部位名称
            'examPartDesc': '' // 检查方法说明
          }
          examItem.examParts.push(examPart)
          examItems.push(examItem)
        }
      })
      console.log('examItems', examItems)
      return examItems
    },
    getHisTree() {
      return new Promise((rs, rj) => {
        this.$refs.tree && this.$refs.tree.setCheckedNodes([])
        this.formdata.bigpart = this.isChangeInfo ? this.formdata.bigpart : ''
        this.formdata.smallpart = this.isChangeInfo ? this.formdata.smallpart : ''
        if (!this.formdata.examClass) {
          this.checkTypeOptions = []
          rs()
        } else {
          const params = {
            HospitalCode: this.hospitalCodeForm || this.hospitalCode,
            Modality: this.formdata.examClass,
            SortType: 2
          }
          getHisTree(params).then(res => {
            this.checkTypeOptions = []
            if (res && res.code === 10000) {
              let depNodes = res.content.childrens
              const _checkTypeData = []
              this.isShowMedicine = this.isEditOrChange != '2' && depNodes.length > 0 && depNodes[0].dep && ['内窥镜', 'ES'].includes(depNodes[0].dep)
              for (let i = 0; i < depNodes.length; i++) {
                let tempLevel1 = { text: depNodes[i].text, level: 1, childrens: [], id: depNodes[i].text }
                // 如果存在部位
                if (depNodes[i].childrens && depNodes[i].childrens.length !== 0) {
                  for (let j = 0; j < depNodes[i].childrens.length; j++) {
                    let level1Children = depNodes[i].childrens
                    // 加上level防止同名
                    let tempLevel2 = { text: level1Children[j].text, level: 2, childrens: [], id: tempLevel1.id + level1Children[j].text + level1Children[j].level, parentId: tempLevel1.text, remart: level1Children[j].remart }
                    if (level1Children[j].childrens && level1Children[j].childrens.length !== 0) {
                      tempLevel2.childrens = level1Children[j].childrens.map(item => {
                        return { text: item.text, level: 3, childrens: [], id: tempLevel2.id + item.text + item.level, parentId: tempLevel2.text, grandId: tempLevel2.parentId }
                      })
                    }
                    tempLevel1.childrens.push(tempLevel2)
                  }
                }
                _checkTypeData.push(tempLevel1)
              }
              this.checkTypeOptions = [..._checkTypeData]
              console.log('getHisTree _checkTypeData', _checkTypeData)
              console.log('this.checkTypeOptions', this.checkTypeOptions)
              rs()
            } else {
              this.loading = false
              rj()
            }
          }).catch(() => {
            this.loading = false
            rj()
          })
        }
      })
    },
    async getDepAreaList() {
      let params = { HospitalCode: this.hospitalCodeForm || this.hospitalCode }
      await this.$store.dispatch('settings/set_depAreaOptions', params)
      if (this.depAreaOptions.length) {
        if (this.depAreaOptions.indexOf(localSetMemoryObj.depArea) > -1) {
          this.depArea = localSetMemoryObj.depArea
        } else {
          this.depArea = this.depAreaOptions[0]
        }
      }
    },
    getModalityTypeList() {
      // if (this.isShowApplyCheck) {
      //   let localSetMemoryObj = getHISRecordDialogMemory()
      // }
      const params = {
        HospitalCode: this.hospitalCodeForm || this.hospitalCode,
        DepArea: this.depArea
      }
      return getModalityTypeList(params).then(res => {
        if (res && res.code === 10000) {
          let depTypes = res.content.list
          // console.log('depTypes', depTypes)
          this.modalitytypeOptions = depTypes
          if (this.modalitytypeOptions.length) {
            if (this.modalitytypeOptions.indexOf(localSetMemoryObj.modalitytype) > -1 && !this.isEditInfo) {
              this.formdata.examClass = localSetMemoryObj.modalitytype
              // if (localSetMemoryObj.depArea == '大麦屿分院') {
              //   this.formdata.examClass = localSetMemoryObj.modalitytype
              // } else {
              //   this.formdata.examClass = localSetMemoryObj.modalitytype
              // }
            } else {
              this.formdata.examClass = this.isChangeInfo ? this.formdata.examClass : this.modalitytypeOptions[0]
            }
          }
        }
      })
    },
    // 优先级改变
    gradeChange() {
      this.appointmentPostMessage()
      // 电子单的传值是emergency手工单的传值是grade
      console.log('this.formdata.grade', this.formdata.grade)
      bus.$emit('changeGrade', this.formdata.grade)
      console.log('$emit_changeGrade')
    },
    // 设备类型改变
    examClassChange() {
      // let params = {
      //   modalitytype: this.formdata.examClass
      // }
      // !this.isEditInfo ? this.$utils.setHISRecordDialogMemory(params) : null
      if (this.formdata.examClass) {
        this.getHisTree()
        this.formdata.examItemsData = []
      } else {
        this.checkTypeOptions = []
      }
    },
    iframePMBack(data) {
      if (data.type === 1) {
        this.$refs.formCheck.resetFields()
        this.resetForm()
        this.$refs.tree && this.$refs.tree.setCheckedKeys([])
      }
    },
    chagnePatientSource() {
      // this.formdata.clinicCode = ''
      // this.formdata.hospizationCode = ''
    },
    async resetForm(fromType) {
      if (fromType === 1) {
        // this.formdata.applyCode = 'S' + id // getRandom() // getNewUUID().replace(/\-/g, '')
        this.formdata.applyDateTime = dateFormatter(new Date())
        this.formdata.visitDateTime = dateFormatter(new Date())
      } else {
        const id = await this.getidgenerator()
        this.formdata.patientSource = this.isChooseAppointed ? 1 : 4
        this.formdata.patientId = 'P' + id // getRandom() // getNewUUID().replace(/\-/g, '')
        this.formdata.applyCode = 'S' + id // getRandom() // getNewUUID().replace(/\-/g, '')
        this.formdata.applyDateTime = dateFormatter(new Date())
        this.formdata.visitDateTime = dateFormatter(new Date())
      }
    },
    // 根据输入身份证号，自动填写 性别、生日、年龄
    idCardChange(e) {
      console.log('idCardChange', e)
      let id = this.formdata.idCard
      if (id && isIdCard(id)) {
        this.formdata.gender = sexById(id)
        this.formdata.birthDate = birthdayById(id)
        this.setAgeValApply(this.formdata.birthDate)
      }
    },
    birthDateChange() {
      console.log('birthDateChange === ', this.formdata.birthDate)
      if (this.formdata.birthDate != null) {
        this.setAgeValApply(dateFormatter(this.formdata.birthDate, false))
      } else {
        this.formdata.patientAge = ''
      }
    },
    getMonthDay(year, month) {
      let days = new Date(year, month + 1, 0).getDate()
      return days
    },
    // 根据出生日期计算年龄
    getAgeApply(strAge) {
      var birArr = strAge.split('-')
      var birYear = birArr[0]
      var birMonth = birArr[1] * 1
      var birDay = birArr[2]

      var d = new Date()
      var nowYear = d.getFullYear()
      var nowMonth = d.getMonth() + 1 // 记得加1
      var nowDay = d.getDate()
      var returnAge; var errFlag = false; var errMsg = ''

      if (birArr == null) {
        return {
          errFlag: true,
          errMsg: '',
          val: ''
        }
      }
      var dBir = new Date(birYear, birMonth - 1, birDay)
      if (dBir.getFullYear() == birYear && (dBir.getMonth() + 1) == birMonth && dBir.getDate() == birDay) {
        if (nowYear == birYear) {
          // 同年
          // returnAge = 0; //同年
          var MonthDiff = nowMonth - birMonth // 计算月
          if (MonthDiff >= 0) {
            if (nowMonth == birMonth) {
              let dayDiff = nowDay - birDay // 计算日
              if (dayDiff >= 0) {
                returnAge = dayDiff + '#天'
              } else {
                errFlag = true
                errMsg = '出生日期晚于今天，数据有误'
              }
            } else if (nowMonth == birMonth + 1) {
              var preMonthDays = this.getMonthDay(birYear, birMonth)
              let dayDiff = nowDay + preMonthDays - birDay // 计算日
              if (dayDiff >= 0) {
                returnAge = dayDiff + '#天'
              } else {
                errFlag = true
                errMsg = '出生日期晚于今天，数据有误'
              }
            } else {
              returnAge = MonthDiff + 1 + '#月'
            }
          } else {
            errFlag = true
            errMsg = '出生日期晚于今天，数据有误'
          }
          return {
            errFlag: errFlag,
            errMsg: errMsg,
            val: returnAge
          }
        } else {
          // 不同年
          var ageDiff = nowYear - birYear // 计算年
          if (ageDiff > 0) {
            if (nowMonth == birMonth) {
              let dayDiff = nowDay - birDay // 计算日
              if (dayDiff < 0) {
                if (ageDiff != 1) {
                  returnAge = (ageDiff - 1) + '#岁'
                } else {
                  returnAge = 11 + '#月'
                }
              } else {
                returnAge = ageDiff + '#岁'
              }
            } else {
              var monthDiff = nowMonth - birMonth // 计算月
              if (monthDiff < 0) {
                // returnAge = ageDiff - 1;
                if (ageDiff != 1) {
                  returnAge = (ageDiff - 1) + '#岁'
                } else {
                  returnAge = Math.abs(nowMonth - birMonth + 12) + '#月'
                }
              } else {
                returnAge = ageDiff + '#岁'
              }
            }
          } else {
            errFlag = true
            errMsg = '出生日期晚于今天，数据有误'// 返回-1 表示出生日期输入错误 晚于今天
          }
          return {
            errFlag: errFlag,
            errMsg: errMsg,
            val: returnAge + '#岁'
          }
        }
      } else {
        return {
          errFlag: true,
          errMsg: '输入的日期格式错误！',
          val: ''
        }
      }
    },
    setAgeValApply(strAge) {
      console.log('setAgeValApply === ', strAge)
      var ageObj = this.getAgeApply(strAge)
      if (!ageObj.errFlag) {
        var ageArr = ageObj.val.split('#')
        this.formdata.patientAgeUnit = ageArr[1]
        this.formdata.patientAge = ageArr[0]
      } else if (ageObj.errMsg != '') {
        this.$alert(ageObj.errMsg, '提示', {
          confirmButtonText: '确定',
          type: 'warning',
          callback: action => {
            this.formdata.birthDate = ''
          }
        })
        return false
      }
    },
    // 监听年龄变化，计算生日
    ageChange() {
      const bday = birthdayByAge(this.formdata.patientAge, this.formdata.patientAgeUnit)
      this.formdata.birthDate = bday
    },
    getParamsString(data) {
      const d = Object.keys(data).map(k => { return `${k}=${data[k]}` })
      return d.join('&')
    },
    idCardBlur(value) {
      console.log('idCardBlur=>', value)
      let id = this.formdata.idCard
      if (id && isIdCard(id)) {
        // //
      } else {
        this.$alert('身份证号格式有误', '提示', {
          confirmButtonText: '确定',
          type: 'warning',
          callback: action => {
            // this.formdata.birthDate = ''
          }
        })
      }
    },
    handleInput(value) {
      let id = value
      if (id.length === 18) {
        this.idCardChange()
      }
    },
    isFresh() {
      this.loading = true
    },
    resetInfo() {
      this.formdata.visitNumber = ''
      this.formdata.wardName = ''
      this.formdata.patientAge = ''
      this.formdata.patientPhone = ''
      this.formdata.address = ''
      this.formdata.bedNo = ''
      this.formdata.idCard = ''
      this.formdata.applyDoctor = ''
      this.formdata.applyDateTime = ''
      this.formdata.applyDepartment = ''
      this.formdata.diseasesHistory = ''
      this.formdata.clinicdiagnosis = ''
      this.formdata.patientName = ''
      this.formdata.cost = 0
      this.formdata.chargeStatus = '未收费'
      this.formdata.examClass = ''
      this.depArea = ''
      this.formdata.grade = ''
      this.formdata.checkcs = ''
      this.formdata.bigpart = ''
      this.formdata.smallpart = ''
      this.formdata.patientSource = 4
      this.formdata.birthDate = ''
      this.formdata.gender = 1
      this.formdata.applyDateTime = dateFormatter(new Date())
      this.formdata.visitDateTime = dateFormatter(new Date())
      // this.defaultIsExpand = true
      // this.handleCheckChange()
      this.checkTreeRow()
      // bus.$emit('isRefreshExpand', true)
      // this.getHisTree()
    }
  }
}
</script>

<style lang="scss" scoped>
.el-radio{
  margin-right: 10px !important;
}
.el-radio__label{
  margin-left: 5px !important;
}
.check_container{
  padding: 3px 10px 10px 10px;
  height: 100%;
  overflow-y: auto;
  padding-bottom: 30px;

  /deep/ .el-form-item{
    margin-bottom: 4px;
  }
  /deep/ .el-form-item__warn{
    display: none;
  }
}
.tree{
  overflow-x: auto;
  width: 100%;
  /deep/ .el-form-item__content{
      display: block;
      .el-tree-node__label{
        width: 100%;
      }
      .el-tree{
          height:100%;
          // & > div > div{
          //   min-width: 240px;
          // }
          .el-tree-node{
              background-color: #fff;
              white-space: normal;
              .el-tree-node__content {
                height: 100%;
                line-height: 22px;
                align-items: start;
              }
          }
      }
  }
}

.el-tree-style{

    /deep/ .el-tree-node {
        position: relative;
    }
    /deep/ .el-tree-node__children {
        padding-left: 16px; // 缩进量
    }

    // 竖线
    /deep/ .el-tree-node::before {
        content: '';
        height: 100%;
        width: 1px;
        position: absolute;
        left: 30px;
        top: 0;
        border-width: 1px;
        border-left: 1px dashed #ddd;
    }
    // 当前层最后一个节点的竖线高度固定
    /deep/ .el-tree-node:last-child::before {
        height: 38px; // 可以自己调节到合适数值
    }

    // 横线
    /deep/ .el-tree-node::after {
        content: '';
        width: 15px;
        height: 20px;
        position: absolute;
        left: 30px;
        top: 12px;
        border-width: 1px;
        border-top: 1px dashed #ddd;
    }

    // 去掉最顶层的虚线，放最下面样式才不会被上面的覆盖了
    & > .el-tree-node::after {
        border-top: none;
    }
    & > .el-tree-node::before {
        border-left: none;
    }

    // 展开关闭的icon
    .el-tree-node__expand-icon {
        font-size: 16px;
        // 叶子节点（无子节点）
        &.is-leaf {
            color: transparent;
            // display: none; // 也可以去掉
        }
    }
}
</style>
